package org.hxyjs.config;

import org.hxyjs.propbean.UpLoadPropBean;
import org.hxyjs.utils.ContextUtils;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration // 表示这个类会被springmvc的容器处理，spring5是无法运行在早期的tomcat版本
// 因为tomcat本身就是一个用java编写的程序 从tomcat8以后才加入了对spring注解的支持
@ComponentScan("org.hxyjs.*") // 简化了自己用代码new出 支持注解的容器类
// AnnotationConfigApplicationContext 不用自己写了
@EnableWebMvc

@EnableAspectJAutoProxy

@EnableTransactionManagement

@EnableCaching

@EnableScheduling

@Import({MyBatisConfig.class, RedisConfig.class, CacheConfig.class})
public class Config implements WebMvcConfigurer {
    /**
     * 得到的访问路径为当前项目端口路径 + /upload/image/
     *
     * @param registry
     */


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /*
         * 说明：增加虚拟路径(经过本人测试：在此处配置的虚拟路径，用springboot内置的tomcat时有效，
         * 用外部的tomcat也有效;所以用到外部的tomcat时不需在tomcat/config下的相应文件配置虚拟路径了,阿里云linux也没问题)
         */
        UpLoadPropBean upLoadPropBean = (UpLoadPropBean) ContextUtils.getSpringMVCContext().getBean("upLoadPropBean");
        System.out.println(upLoadPropBean.upload + " " + upLoadPropBean.mapping);
        registry.addResourceHandler(upLoadPropBean.mapping).addResourceLocations(upLoadPropBean.upload);
        //registry.addResourceHandler("/upload/images/**").addResourceLocations("file:c:/upload/");
    }

    @Bean("propertyConfigurer")  //propertie的配置器将指定的properies添加
    public PropertyPlaceholderConfigurer getPropertyPalce() {
        PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();//生成配置类
        //生成资源数组
        ClassPathResource[] classPathResources = {new ClassPathResource("log4j.properties"),
                new ClassPathResource("log4jdbc.log4j2.properties")};
        //classpth就是部署出来的classes的根目录
        propertyPlaceholderConfigurer.setLocations(classPathResources);//将指定资源注册加载
        return propertyPlaceholderConfigurer;
    }

}
